package com.ruoyi.system.service.impl;

public class BinaryTreeInverter {
    public static void main(String[] args) {
        // 创建一个示例二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);

        System.out.println("Original tree:");
        printTree(root);

        // 反转二叉树
        invertTree(root);

        System.out.println("\nInverted tree:");
        printTree(root);
    }

    // 反转二叉树的方法
    public static TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        // 交换左右子树
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        // 递归反转左右子树
        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    // 打印二叉树的方法（前序遍历）
    public static void printTree(TreeNode root) {
        if (root != null) {
            System.out.print(root.val + " ");
            printTree(root.left);
            printTree(root.right);
        }
    }
}
